<template>
  <div class="app-container">
    <!-- 页面标题 -->
    <ContentWrap>
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span style="font-size: 18px; font-weight: bold;">文件上传测试页面</span>
          </div>
        </template>
        <el-alert
          title="此页面用于测试文件和绘本上传功能是否正常工作"
          type="info"
          :closable="false"
          style="margin-bottom: 20px"
        />

        <!-- 上传模式选择 -->
        <div style="margin-bottom: 20px;">
          <el-radio-group v-model="uploadMode" @change="handleUploadModeChange">
            <el-radio value="general">通用上传模式（基础设施接口）</el-radio>
            <el-radio value="business">业务上传模式（绘本路径管理）</el-radio>
          </el-radio-group>
          <div style="margin-top: 10px; font-size: 12px; color: #666;">
            <div v-if="uploadMode === 'general'">
              <strong>通用模式：</strong>文件存储路径格式：<code>日期/文件名_时间戳.扩展名</code>
            </div>
            <div v-else>
              <strong>业务模式：</strong>文件存储路径格式：<code>业务分类/子分类/日期/文件名_时间戳.扩展名</code>
            </div>
          </div>
        </div>
      </el-card>
    </ContentWrap>

    <!-- 文件上传测试区域 -->
    <ContentWrap>
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>📁 普通文件上传测试</span>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-upload
              ref="fileUploadRef"
              class="upload-demo"
              :action="uploadFileUrl"
              :headers="uploadHeaders"
              :on-success="handleFileSuccess"
              :on-error="handleFileError"
              :before-upload="beforeFileUpload"
              :file-list="fileList"
              multiple
              drag
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  支持jpg/png/gif/pdf/doc/docx等格式，单个文件大小不超过10MB
                </div>
              </template>
            </el-upload>
          </el-col>
          
          <el-col :span="12">
            <div class="upload-result">
              <h4>上传结果：</h4>
              <el-scrollbar height="200px">
                <div v-for="(result, index) in uploadResults" :key="index" class="result-item">
                  <el-tag :type="result.success ? 'success' : 'danger'" style="margin-bottom: 5px;">
                    {{ result.success ? '✓' : '✗' }} {{ result.fileName }}
                  </el-tag>
                  <div v-if="result.success" class="file-info">
                    <p><strong>文件URL:</strong> <a :href="result.url" target="_blank">{{ result.url }}</a></p>
                    <p><strong>文件大小:</strong> {{ formatFileSize(result.size) }}</p>
                  </div>
                  <div v-else class="error-info">
                    <p style="color: red;"><strong>错误:</strong> {{ result.error }}</p>
                  </div>
                </div>
              </el-scrollbar>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </ContentWrap>

    <!-- 绘本集管理区域 -->
    <ContentWrap>
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>📚 绘本集管理系统</span>
            <div class="header-buttons">
              <el-button type="primary" @click="openBookSetManager">打开绘本集管理器</el-button>
              <el-button type="success" @click="openBookSetManagerWithDemo">体验演示</el-button>
            </div>
          </div>
        </template>

        <el-alert
          title="新功能：完整的绘本集创建和管理工具，支持多绘本、多页面的结构化管理"
          type="success"
          :closable="false"
          style="margin-bottom: 20px"
        />

        <el-row :gutter="20">
          <el-col :span="12">
            <div class="feature-list">
              <h4>功能特点：</h4>
              <ul>
                <li>✅ 分步骤引导创建绘本集</li>
                <li>✅ 支持多个绘本管理</li>
                <li>✅ 每个绘本支持多页面</li>
                <li>✅ 页面图片、文本、音频一体化管理</li>
                <li>✅ 实时预览和验证</li>
                <li>✅ 支持拖拽排序</li>
              </ul>
            </div>
          </el-col>

          <el-col :span="12">
            <div class="usage-guide">
              <h4>使用流程：</h4>
              <el-steps direction="vertical" :space="60" :active="4">
                <el-step title="基本信息" description="设置绘本集标题、分类、封面等" />
                <el-step title="绘本管理" description="添加多个绘本，设置封面和描述" />
                <el-step title="页面管理" description="为每个绘本添加页面、图片、文本、音频" />
                <el-step title="预览提交" description="预览完整内容并提交创建" />
              </el-steps>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </ContentWrap>

    <!-- 绘本上传测试区域 -->
    <ContentWrap>
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>📚 绘本文件上传测试（简单模式）</span>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form :model="bookForm" label-width="100px">
              <el-form-item label="绘本标题">
                <el-input v-model="bookForm.title" placeholder="请输入绘本标题" />
              </el-form-item>
              
              <el-form-item label="绘本封面">
                <el-upload
                  ref="coverUploadRef"
                  class="avatar-uploader"
                  :action="getCurrentUploadUrl('cover')"
                  :headers="uploadHeaders"
                  :show-file-list="false"
                  :on-success="handleCoverSuccess"
                  :before-upload="beforeCoverUpload"
                  :name="getUploadParamName('cover')"
                >
                  <img v-if="bookForm.coverUrl" :src="bookForm.coverUrl" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
              </el-form-item>
              
              <el-form-item label="绘本页面">
                <el-upload
                  ref="pagesUploadRef"
                  class="upload-demo"
                  :action="getCurrentUploadUrl('pages')"
                  :headers="uploadHeaders"
                  :on-success="handlePagesSuccess"
                  :on-error="handlePagesError"
                  :before-upload="beforePagesUpload"
                  :file-list="pagesList"
                  :name="getUploadParamName('pages')"
                  multiple
                  accept="image/*"
                >
                  <el-button type="primary">选择图片文件</el-button>
                  <template #tip>
                    <div class="el-upload__tip">
                      只能上传jpg/png格式的图片文件，且不超过5MB
                    </div>
                  </template>
                </el-upload>
              </el-form-item>
              
              <el-form-item label="音频文件">
                <el-upload
                  ref="audioUploadRef"
                  class="upload-demo"
                  :action="getCurrentUploadUrl('audio')"
                  :headers="uploadHeaders"
                  :on-success="handleAudioSuccess"
                  :on-error="handleAudioError"
                  :before-upload="beforeAudioUpload"
                  :file-list="audioList"
                  :name="getUploadParamName('audio')"
                  multiple
                  accept="audio/*"
                >
                  <el-button type="primary">选择音频文件</el-button>
                  <template #tip>
                    <div class="el-upload__tip">
                      只能上传mp3/wav/m4a格式的音频文件，且不超过20MB
                    </div>
                  </template>
                </el-upload>
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" @click="testBookUpload">测试绘本上传</el-button>
                <el-button @click="resetBookForm">重置</el-button>
              </el-form-item>
            </el-form>
          </el-col>
          
          <el-col :span="12">
            <div class="book-preview">
              <h4>绘本预览：</h4>
              <div v-if="bookForm.title" class="book-info">
                <p><strong>标题:</strong> {{ bookForm.title }}</p>
                <div v-if="bookForm.coverUrl" class="cover-preview">
                  <p><strong>封面:</strong></p>
                  <img :src="bookForm.coverUrl" style="width: 100px; height: 100px; object-fit: cover;" />
                </div>
                <div v-if="bookForm.pages.length > 0" class="pages-preview">
                  <p><strong>页面 ({{ bookForm.pages.length }}张):</strong></p>
                  <div class="pages-grid">
                    <img 
                      v-for="(page, index) in bookForm.pages" 
                      :key="index" 
                      :src="page.url" 
                      :title="page.name"
                      style="width: 60px; height: 60px; object-fit: cover; margin: 2px;"
                    />
                  </div>
                </div>
                <div v-if="bookForm.audios.length > 0" class="audios-preview">
                  <p><strong>音频 ({{ bookForm.audios.length }}个):</strong></p>
                  <div v-for="(audio, index) in bookForm.audios" :key="index" class="audio-item">
                    <audio controls style="width: 100%; margin-bottom: 5px;">
                      <source :src="audio.url" type="audio/mpeg" />
                      您的浏览器不支持音频播放。
                    </audio>
                    <p style="font-size: 12px; color: #666;">{{ audio.name }}</p>
                  </div>
                </div>
              </div>
              <div v-else class="no-data">
                <p style="color: #999;">请填写绘本信息并上传文件</p>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </ContentWrap>

    <!-- 磨耳朵音频上传测试区域 -->
    <ContentWrap>
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>🎵 磨耳朵音频上传测试</span>
          </div>
        </template>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form :model="audioForm" label-width="120px">
              <el-form-item label="音频标题">
                <el-input v-model="audioForm.title" placeholder="请输入音频标题" />
              </el-form-item>

              <el-form-item label="音频分类">
                <el-select v-model="audioForm.category" placeholder="请选择音频分类" style="width: 100%">
                  <el-option label="英文" value="english" />
                  <el-option label="中文" value="chinese" />
                  <el-option label="双语" value="bilingual" />
                </el-select>
              </el-form-item>

              <el-form-item label="语言类型">
                <el-select v-model="audioForm.language" placeholder="请选择语言类型" style="width: 100%">
                  <el-option label="英文 (en)" value="en" />
                  <el-option label="中文 (zh)" value="zh" />
                  <el-option label="双语 (bilingual)" value="bilingual" />
                </el-select>
              </el-form-item>

              <el-form-item label="音频文件">
                <el-upload
                  ref="audioResourceUploadRef"
                  class="upload-demo"
                  :action="getCurrentUploadUrl('audioResource')"
                  :headers="uploadHeaders"
                  :on-success="handleAudioResourceSuccess"
                  :on-error="handleAudioResourceError"
                  :before-upload="beforeAudioResourceUpload"
                  :name="getUploadParamName('audioResource')"
                  :data="getAudioResourceFormData"
                  :show-file-list="false"
                  accept="audio/*"
                >
                  <el-button type="primary">选择音频文件</el-button>
                  <template #tip>
                    <div class="el-upload__tip">
                      只能上传mp3/wav/m4a格式的音频文件，且不超过50MB
                    </div>
                  </template>
                </el-upload>
                <div v-if="audioForm.audioUrl" style="margin-top: 10px;">
                  <el-tag type="success">✓ 音频已上传</el-tag>
                  <audio controls style="width: 100%; margin-top: 5px;">
                    <source :src="audioForm.audioUrl" type="audio/mpeg" />
                    您的浏览器不支持音频播放
                  </audio>
                </div>
              </el-form-item>

              <el-form-item label="音频封面">
                <el-upload
                  ref="audioCoverUploadRef"
                  class="avatar-uploader"
                  :action="getCurrentUploadUrl('audioCover')"
                  :headers="uploadHeaders"
                  :show-file-list="false"
                  :on-success="handleAudioCoverSuccess"
                  :before-upload="beforeAudioCoverUpload"
                  :name="getUploadParamName('audioCover')"
                >
                  <img v-if="audioForm.coverUrl" :src="audioForm.coverUrl" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="testAudioUpload">测试音频上传</el-button>
                <el-button @click="resetAudioForm">重置</el-button>
              </el-form-item>
            </el-form>
          </el-col>

          <el-col :span="12">
            <div class="audio-preview">
              <h4>音频预览：</h4>
              <div v-if="audioForm.title" class="audio-info">
                <p><strong>标题:</strong> {{ audioForm.title }}</p>
                <p><strong>分类:</strong> {{ getAudioCategoryText(audioForm.category) }}</p>
                <p><strong>语言:</strong> {{ getAudioLanguageText(audioForm.language) }}</p>
                <div v-if="audioForm.coverUrl" class="cover-preview">
                  <p><strong>封面:</strong></p>
                  <img :src="audioForm.coverUrl" style="width: 100px; height: 100px; object-fit: cover;" />
                </div>
                <div v-if="audioForm.audioUrl" class="audio-preview-player">
                  <p><strong>音频:</strong></p>
                  <audio controls style="width: 100%;">
                    <source :src="audioForm.audioUrl" type="audio/mpeg" />
                    您的浏览器不支持音频播放
                  </audio>
                </div>
              </div>
              <div v-else class="no-data">
                <p style="color: #999;">请填写音频信息并上传文件</p>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </ContentWrap>

    <!-- 测试结果统计 -->
    <ContentWrap>
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>📊 测试结果统计</span>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="6">
            <el-statistic title="总上传次数" :value="statistics.totalUploads" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="成功次数" :value="statistics.successUploads" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="失败次数" :value="statistics.failedUploads" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="成功率" :value="statistics.successRate" suffix="%" />
          </el-col>
        </el-row>
        
        <div style="margin-top: 20px;">
          <el-button type="danger" @click="clearTestData">清空测试数据</el-button>
          <el-button type="info" @click="exportTestResults">导出测试结果</el-button>
        </div>
      </el-card>
    </ContentWrap>

    <!-- 绘本集管理器弹窗 -->
    <el-dialog
      v-model="bookSetManagerVisible"
      title="绘本集管理器"
      width="95%"
      top="5vh"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="bookset-manager-dialog"
    >
      <BookSetManager
        v-if="bookSetManagerVisible"
        @close="closeBookSetManager"
        @success="handleBookSetSuccess"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled, Plus } from '@element-plus/icons-vue'
import { getAccessToken } from '@/utils/auth'
import BookSetManager from './components/BookSetManager.vue'

defineOptions({ name: 'InfraTest' })

// 上传配置
const uploadFileUrl = import.meta.env.VITE_BASE_URL + '/admin-api/infra/file/upload'
const uploadHeaders = {
  Authorization: 'Bearer ' + getAccessToken()
}

// 绘本业务上传配置（使用路径管理系统）
const bookSetId = 999 // 测试用的绘本集ID
const bookId = 999 // 测试用的绘本ID
const bookUploadUrls = {
  cover: import.meta.env.VITE_BASE_URL + `/admin-api/reading/book-file/book-set/${bookSetId}/book/${bookId}/cover`,
  pages: (pageNumber) => import.meta.env.VITE_BASE_URL + `/admin-api/reading/book-file/book-set/${bookSetId}/book/${bookId}/page/${pageNumber}`,
  audio: import.meta.env.VITE_BASE_URL + `/admin-api/reading/book-file/book-set/${bookSetId}/book/${bookId}/audio`
}

// 上传模式
const uploadMode = ref('general') // 'general' | 'business'

// 绘本集管理器
const bookSetManagerVisible = ref(false)

// 文件上传相关
const fileUploadRef = ref()
const fileList = ref([])
const uploadResults = ref([])

// 绘本上传相关
const coverUploadRef = ref()
const pagesUploadRef = ref()
const audioUploadRef = ref()
const pagesList = ref([])
const audioList = ref([])

const bookForm = reactive({
  title: '',
  coverUrl: '',
  pages: [],
  audios: []
})

// 磨耳朵音频上传相关
const audioResourceUploadRef = ref()
const audioCoverUploadRef = ref()
const testAudioId = 999 // 测试用的音频ID

const audioUploadUrls = {
  resource: import.meta.env.VITE_BASE_URL + '/admin-api/reading/audio-file/resource',
  cover: (audioId) => import.meta.env.VITE_BASE_URL + `/admin-api/reading/audio-file/audio/${audioId}/cover`
}

const audioForm = reactive({
  title: '',
  category: 'english',
  language: 'en',
  audioUrl: '',
  coverUrl: ''
})

// 统计数据
const statistics = reactive({
  totalUploads: 0,
  successUploads: 0,
  failedUploads: 0
})

const successRate = computed(() => {
  if (statistics.totalUploads === 0) return 0
  return Math.round((statistics.successUploads / statistics.totalUploads) * 100)
})

// 更新统计数据
statistics.successRate = successRate

// 获取当前上传URL
const getCurrentUploadUrl = (type) => {
  if (uploadMode.value === 'business') {
    switch (type) {
      case 'cover':
        return bookUploadUrls.cover
      case 'pages':
        return bookUploadUrls.pages(1) // 默认页码1
      case 'audio':
        return bookUploadUrls.audio
      case 'audioResource':
        return audioUploadUrls.resource
      case 'audioCover':
        return audioUploadUrls.cover(testAudioId)
      default:
        return uploadFileUrl
    }
  }
  return uploadFileUrl
}

// 获取上传参数名
const getUploadParamName = (type) => {
  if (uploadMode.value === 'business') {
    switch (type) {
      case 'cover':
        return 'cover'
      case 'pages':
        return 'page'
      case 'audio':
        return 'audio'
      case 'audioResource':
        return 'audio'
      case 'audioCover':
        return 'cover'
      default:
        return 'file'
    }
  }
  return 'file'
}

// 处理上传模式变化
const handleUploadModeChange = (mode) => {
  ElMessage.info(`已切换到${mode === 'general' ? '通用' : '业务'}上传模式`)
}

// 文件上传处理
const beforeFileUpload = (file) => {
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('上传文件大小不能超过 10MB!')
    return false
  }
  return true
}

const handleFileSuccess = (response, file) => {
  statistics.totalUploads++
  if (response.code === 0) {
    statistics.successUploads++
    uploadResults.value.unshift({
      success: true,
      fileName: file.name,
      url: response.data,
      size: file.size
    })
    ElMessage.success(`文件 ${file.name} 上传成功!`)
  } else {
    statistics.failedUploads++
    uploadResults.value.unshift({
      success: false,
      fileName: file.name,
      error: response.msg || '上传失败'
    })
    ElMessage.error(`文件 ${file.name} 上传失败: ${response.msg}`)
  }
}

const handleFileError = (error, file) => {
  statistics.totalUploads++
  statistics.failedUploads++
  uploadResults.value.unshift({
    success: false,
    fileName: file.name,
    error: error.message || '网络错误'
  })
  ElMessage.error(`文件 ${file.name} 上传失败: ${error.message}`)
}

// 绘本封面上传
const beforeCoverUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2
  
  if (!isImage) {
    ElMessage.error('只能上传图片格式的文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleCoverSuccess = (response) => {
  if (response.code === 0) {
    bookForm.coverUrl = response.data
    ElMessage.success('封面上传成功!')
  } else {
    ElMessage.error('封面上传失败: ' + response.msg)
  }
}

// 绘本页面上传
const beforePagesUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5
  
  if (!isImage) {
    ElMessage.error('只能上传图片格式的文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('上传图片大小不能超过 5MB!')
    return false
  }
  return true
}

const handlePagesSuccess = (response, file) => {
  if (response.code === 0) {
    bookForm.pages.push({
      name: file.name,
      url: response.data
    })
    ElMessage.success(`页面 ${file.name} 上传成功!`)
  } else {
    ElMessage.error(`页面 ${file.name} 上传失败: ${response.msg}`)
  }
}

const handlePagesError = (error, file) => {
  ElMessage.error(`页面 ${file.name} 上传失败: ${error.message}`)
}

// 音频上传
const beforeAudioUpload = (file) => {
  const isAudio = file.type.startsWith('audio/')
  const isLt20M = file.size / 1024 / 1024 < 20
  
  if (!isAudio) {
    ElMessage.error('只能上传音频格式的文件!')
    return false
  }
  if (!isLt20M) {
    ElMessage.error('上传音频大小不能超过 20MB!')
    return false
  }
  return true
}

const handleAudioSuccess = (response, file) => {
  if (response.code === 0) {
    bookForm.audios.push({
      name: file.name,
      url: response.data
    })
    ElMessage.success(`音频 ${file.name} 上传成功!`)
  } else {
    ElMessage.error(`音频 ${file.name} 上传失败: ${response.msg}`)
  }
}

const handleAudioError = (error, file) => {
  ElMessage.error(`音频 ${file.name} 上传失败: ${error.message}`)
}

// 工具函数
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 测试绘本上传
const testBookUpload = () => {
  if (!bookForm.title) {
    ElMessage.warning('请输入绘本标题!')
    return
  }
  
  ElMessage.success('绘本信息测试完成!')
  console.log('绘本测试数据:', bookForm)
}

// 重置绘本表单
const resetBookForm = () => {
  bookForm.title = ''
  bookForm.coverUrl = ''
  bookForm.pages = []
  bookForm.audios = []
  pagesList.value = []
  audioList.value = []
}

// 清空测试数据
const clearTestData = () => {
  ElMessageBox.confirm('确定要清空所有测试数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    uploadResults.value = []
    statistics.totalUploads = 0
    statistics.successUploads = 0
    statistics.failedUploads = 0
    resetBookForm()
    resetAudioForm()
    ElMessage.success('测试数据已清空!')
  })
}

// 导出测试结果
const exportTestResults = () => {
  const results = {
    statistics: statistics,
    uploadResults: uploadResults.value,
    bookForm: bookForm,
    audioForm: audioForm,
    timestamp: new Date().toISOString()
  }
  
  const dataStr = JSON.stringify(results, null, 2)
  const dataBlob = new Blob([dataStr], { type: 'application/json' })
  const url = URL.createObjectURL(dataBlob)
  const link = document.createElement('a')
  link.href = url
  link.download = `upload-test-results-${new Date().getTime()}.json`
  link.click()
  URL.revokeObjectURL(url)
  
  ElMessage.success('测试结果已导出!')
}

// =============================================
// 磨耳朵音频上传相关方法
// =============================================

// 获取音频资源上传的表单数据
const getAudioResourceFormData = computed(() => {
  return {
    category: audioForm.category,
    language: audioForm.language
  }
})

// 音频资源上传前验证
const beforeAudioResourceUpload = (file) => {
  const isAudio = file.type.startsWith('audio/')
  const isLt50M = file.size / 1024 / 1024 < 50

  if (!isAudio) {
    ElMessage.error('只能上传音频文件!')
    return false
  }
  if (!isLt50M) {
    ElMessage.error('音频文件大小不能超过 50MB!')
    return false
  }

  if (!audioForm.category) {
    ElMessage.error('请先选择音频分类!')
    return false
  }

  if (!audioForm.language) {
    ElMessage.error('请先选择语言类型!')
    return false
  }

  statistics.totalUploads++
  return true
}

// 音频资源上传成功
const handleAudioResourceSuccess = (response, file) => {
  console.log('音频资源上传成功:', response)
  if (response.code === 0) {
    audioForm.audioUrl = response.data
    statistics.successUploads++
    ElMessage.success('音频上传成功!')
  } else {
    statistics.failedUploads++
    ElMessage.error('音频上传失败: ' + response.msg)
  }
}

// 音频资源上传失败
const handleAudioResourceError = (err, file) => {
  console.error('音频资源上传失败:', err)
  statistics.failedUploads++
  ElMessage.error('音频上传失败: ' + err.message)
}

// 音频封面上传前验证
const beforeAudioCoverUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片文件大小不能超过 5MB!')
    return false
  }

  statistics.totalUploads++
  return true
}

// 音频封面上传成功
const handleAudioCoverSuccess = (response, file) => {
  console.log('音频封面上传成功:', response)
  if (response.code === 0) {
    audioForm.coverUrl = response.data
    statistics.successUploads++
    ElMessage.success('封面上传成功!')
  } else {
    statistics.failedUploads++
    ElMessage.error('封面上传失败: ' + response.msg)
  }
}

// 测试音频上传
const testAudioUpload = () => {
  if (!audioForm.title) {
    ElMessage.warning('请输入音频标题')
    return
  }

  if (!audioForm.audioUrl) {
    ElMessage.warning('请先上传音频文件')
    return
  }

  ElMessage.success('音频信息验证通过，可以进行完整的音频上传测试!')
  console.log('音频表单数据:', audioForm)
}

// 重置音频表单
const resetAudioForm = () => {
  audioForm.title = ''
  audioForm.category = 'english'
  audioForm.language = 'en'
  audioForm.audioUrl = ''
  audioForm.coverUrl = ''
}

// 获取音频分类显示文本
const getAudioCategoryText = (category) => {
  const categoryMap = {
    'english': '英文',
    'chinese': '中文',
    'bilingual': '双语'
  }
  return categoryMap[category] || category
}

// 获取音频语言显示文本
const getAudioLanguageText = (language) => {
  const languageMap = {
    'en': '英文',
    'zh': '中文',
    'bilingual': '双语'
  }
  return languageMap[language] || language
}

// =============================================
// 绘本集管理器相关方法
// =============================================

// 打开绘本集管理器
const openBookSetManager = () => {
  bookSetManagerVisible.value = true
}

// 打开绘本集管理器（带演示数据）
const openBookSetManagerWithDemo = () => {
  bookSetManagerVisible.value = true
  // 这里可以预填充一些演示数据
}

// 关闭绘本集管理器
const closeBookSetManager = () => {
  bookSetManagerVisible.value = false
}

// 绘本集创建成功回调
const handleBookSetSuccess = (bookSetData) => {
  ElMessage.success('绘本集创建成功!')
  console.log('创建的绘本集数据:', bookSetData)
  closeBookSetManager()
}
</script>

<style scoped>
.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.upload-result {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
  background-color: #fafafa;
}

.result-item {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.result-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.file-info, .error-info {
  margin-top: 5px;
  font-size: 12px;
}

.file-info p, .error-info p {
  margin: 2px 0;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: 0.2s;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.book-preview {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
  background-color: #fafafa;
  height: 400px;
  overflow-y: auto;
}

.pages-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.audio-item {
  margin-bottom: 10px;
}

.no-data {
  text-align: center;
  padding: 50px 0;
}

.audio-preview {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
  background-color: #fafafa;
  height: 400px;
  overflow-y: auto;
}

.audio-info {
  font-size: 14px;
}

.audio-info p {
  margin: 8px 0;
  line-height: 1.5;
}

.cover-preview {
  margin: 10px 0;
}

.audio-preview-player {
  margin: 10px 0;
}

.feature-list {
  margin-top: 10px;
}

.feature-list h4 {
  margin-bottom: 10px;
  color: #409eff;
}

.feature-list ul {
  margin: 0;
  padding-left: 20px;
}

.feature-list li {
  margin-bottom: 5px;
  line-height: 1.5;
}

.usage-guide {
  margin-top: 10px;
}

.usage-guide h4 {
  margin-bottom: 15px;
  color: #409eff;
}

.usage-guide .el-steps {
  margin-left: 10px;
}

.bookset-manager-dialog {
  .el-dialog {
    height: 90vh;
    max-height: 90vh;
    margin: 0 auto;
    display: flex;
    flex-direction: column;
  }

  .el-dialog__header {
    flex-shrink: 0;
  }

  .el-dialog__body {
    padding: 10px 20px;
    flex: 1;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }

  .bookset-manager {
    height: 100%;
    display: flex;
    flex-direction: column;
  }
}

.header-buttons {
  display: flex;
  gap: 10px;
}
</style>
